<?php

namespace app\admin\model;

use app\admin\controller\Zlog;
use app\common\logic\OrgLogic;
use app\common\model\MoneyLog;
use think\Db;
use think\Exception;
use think\Model;

class User extends Model
{

    // 表名
    protected $name = 'user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'prevtime_text',
        'logintime_text',
        'jointime_text',
        'type_text',
    ];

    public function getOriginData()
    {
        return $this->origin;
    }
    public function getTypeList()
    {
        return ['0' => __('Type 0'), '1' => __('Type 1'), '3' => __('Type 3')];
    }
    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            //如果有修改密码
            if (isset($changed['password'])) {
                if ($changed['password']) {
                    $salt = \fast\Random::alnum();
                    $row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
                    $row->salt = $salt;
                } else {
                    unset($row->password);
                }
            }
        });


        self::beforeUpdate(function ($row) {
            $changedata = $row->getChangedData();
            if (isset($changedata['money'])) {
                $origin = $row->getOriginData();
                MoneyLog::create(['user_id' => $row['id'], 'money' => $changedata['money'] - $origin['money'], 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => '管理员变更金额']);
            }
        });
    }

    public function getGenderList()
    {
        return ['1' => __('Male'), '0' => __('Female')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }

    public function getPrevtimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['prevtime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getLogintimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['logintime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getJointimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['jointime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPrevtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setLogintimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setJointimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    public function group()
    {
        return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function orggroup()
    {
        return $this->belongsTo('OrgGradeUser', 'id', 'user_id', [], 'LEFT')->setEagerlyType(0);
    }
    public function getOrgCateId($id)
    {
        return Db::name($this->name)->where('id', '=', $id)->value('org_cate_id');
    }

    public function input_csv($handle, $groupid, $org_cate_id)
    {
        $child = (new OrgLogic())->getCateChild(ORG_CATE_ID);
        $out = array();
        $n =$m= 0;
        while ($data = fgetcsv($handle)) {
            $num = count($data);
            for ($i = 0; $i < $num; $i++) {
                if (!empty($data[$i])) {
//                    $data[$i] = mb_convert_encoding(trim($data[$i]), "UTF-8", "GBK");
                    $data[$i] = iconv(mb_detect_encoding(trim($data[$i])
                        , array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5')), 'utf-8//IGNORE', trim($data[$i]));
                    $out[$n][$i] = $data[$i];
                } else {
                    $out[$n][$i] = "";
                }
            }
            if(count($out)>=10){
                $m += $this->importCSV($out, $groupid, $org_cate_id,$child);
                $out=[];
                $out[0] = ['学生学号','学生姓名','性别','年龄','用户名','密码','家长用户名','家长密码'];
            }
            $n++;
        }
        if(count($out)>0){
            $m += $this->importCSV($out, $groupid, $org_cate_id,$child);
        }
        return $m;
    }
    public function importCSV($result, $groupid, $org_cate_id,$child){

        unset($result[0]);
        $num = 0;
        foreach ($result as $val){
            $info['number_id'] = $val[0];
            if(empty($info['number_id'])){
                continue;
            }
            $total = Db::name('user')->where('number_id', $info['number_id'])->where('org_cate_id','in', $child)->count();
            if($total > 0){
                continue;
            }
            $info['nickname'] = $val[1];
            $info['gender'] = $val[2] == '男'?1:2;
            $info['age'] = $val[3];
            $info['username'] = $val[4];
            if(empty($info['username'])){
                continue;
            }
            $total = Db::name('user')->where('username', $info['username'])->where('org_cate_id','in', $child)->count();
            if($total > 0){
                continue;
            }
            $info['password'] = md5(md5($val[5]));
            if(empty($info['password'])){
                continue;
            }
            $info['org_cate_id'] = $org_cate_id;
            $info['user_type'] = 0;
            $info['jointime'] = time();
            $info['createtime'] = time();
            $info['status'] = 'normal';
            $parent['username'] = $val[6];
            if(empty($parent['username'])){
                continue;
            }
            if($parent['username'] == $info['username']){
                continue;
            }
            $total = Db::name('user')->where('username', $parent['username'])->where('org_cate_id',ORG_CATE_ID)->count();
            if($total > 0){
                continue;
            }

            $parent['password'] = md5(md5($val[7]));
            if(empty($parent['password'])){
                continue;
            }
            $parent['org_cate_id'] = $org_cate_id;
            $parent['user_type'] = 1;
            $parent['jointime'] = time();
            $parent['createtime'] = time();
            $parent['status'] = 'normal';
            Db::startTrans();
            try {
                //入库
                $p_id = Db::name('user')->insertGetId($parent);
                if($p_id > 0){
                    Db::name('org_grade_user')->insertGetId(['org_grade_id'=>$groupid, 'user_id'=>$p_id]);
                    $info['parent_id'] = $p_id;
                    $id = Db::name('user')->insertGetId($info);
                    if($id > 0){
                        Db::name('org_grade_user')->insertGetId(['org_grade_id'=>$groupid, 'user_id'=>$id]);
                    }
                }
                Db::commit();
                $num++;
            }catch (Exception $e){
                Db::rollback();
                return false;
            }
        }
        return $num;
    }

    public function input_csv2($handle, $org_cate_id)
    {
        $child = (new OrgLogic())->getCateChild(ORG_CATE_ID);
        $out = array();
        $n =$m= 0;
        while ($data = fgetcsv($handle)) {
            $num = count($data);
            for ($i = 0; $i < $num; $i++) {
                if (!empty($data[$i])) {
//                    $data[$i] = mb_convert_encoding(trim($data[$i]), "UTF-8", "GBK");
                    $data[$i] = iconv(mb_detect_encoding(trim($data[$i])
                        , array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5')), 'utf-8//IGNORE', trim($data[$i]));
                    $out[$n][$i] = $data[$i];
                } else {
                    $out[$n][$i] = "";
                }
            }
            if(count($out)>=10){
                $m += $this->importCSV2($out, $org_cate_id,$child);
                $out=[];
                $out[0] = ['工号','姓名','性别','年龄','用户名','密码'];
            }
            $n++;
        }
        if(count($out)>0){
            $m += $this->importCSV2($out, $org_cate_id,$child);
        }
        return $m;
    }
    public function importCSV2($result, $org_cate_id,$child){
        unset($result[0]);
        $num = 0;
        foreach ($result as $val){
            $info['number_id'] = $val[0];
            if(empty($info['number_id'])){
                continue;
            }
            $total = Db::name('user')->where('number_id', $info['number_id'])->where('org_cate_id','in', $child)->count();
            if($total > 0){
                continue;
            }
            $info['nickname'] = $val[1];
            if(empty($info['nickname'])){
                continue;
            }
            $info['gender'] = $val[2] == '男'?1:2;
            $info['age'] = $val[3];
            $info['username'] = $val[4];
            if(empty($info['username'])){
                continue;
            }
            $total = Db::name('user')->where('username', $info['username'])->where('org_cate_id','in', $child)->count();
            if($total > 0){
                continue;
            }
            $info['password'] = md5(md5($val[5]));
            if(empty($info['password'])){
                continue;
            }
            $info['org_cate_id'] = $org_cate_id;
            $info['user_type'] = 3;
            $info['jointime'] = time();
            $info['createtime'] = time();
            $info['status'] = 'normal';
            Db::startTrans();
            try {
                //入库
                Db::name('user')->insertGetId($info);
                Db::commit();
                $num++;
            }catch (Exception $e){
                Db::rollback();
                return false;
            }
        }
        return $num;
    }

}
